<%#
 Copyright 2013-2019 the original author or authors from the JHipster project.

 This file is part of the JHipster project, see https://www.jhipster.tech/
 for more information.

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
-%>
import { Injectable } from '@angular/core';
<%_ if (authenticationType === 'oauth2') { _%>
import { Location } from '@angular/common';
<%_ } _%>
import { AccountService } from 'app/core/auth/account.service';
<%_ if (authenticationType === 'jwt' || authenticationType === 'uaa') { _%>
import { AuthServerProvider } from 'app/core/auth/auth-jwt.service';
<%_ } else if (authenticationType === 'session' || authenticationType === 'oauth2') { _%>
import { AuthServerProvider } from 'app/core/auth/auth-session.service';
<%_ } _%>
<%_ if (websocket === 'spring-websocket') { _%>
import { <%=jhiPrefixCapitalized%>TrackerService } from 'app/core/tracker/tracker.service';
<%_ } _%>

@Injectable({providedIn: 'root'})
export class LoginService {

    constructor(
        private accountService: AccountService,
        <%_ if (websocket === 'spring-websocket') { _%>
        private trackerService: <%=jhiPrefixCapitalized%>TrackerService,
        <%_ } _%>
        <%_ if (authenticationType === 'oauth2') { _%>
        private location: Location,
        <%_ } _%>
        private authServerProvider: AuthServerProvider
    ) {}

    <%_ if (authenticationType === 'oauth2') { _%>
    login() {
        // If you have configured multiple OIDC providers, then, you can update this URL to /login.
        // It will show a Spring Security generated login page with links to configured OIDC providers.
        location.href = `${location.origin}${this.location.prepareExternalUrl('oauth2/authorization/oidc')}`;
    }
    <%_ } else { _%>
    login(credentials, callback?) {
        const cb = callback || function() {};

        return new Promise((resolve, reject) => {
            this.authServerProvider.login(credentials).subscribe((data) => {
                this.accountService.identity(true).then((account) => {
                    <%_ if (websocket === 'spring-websocket') { _%>
                    this.trackerService.sendActivity();
                    <%_ } _%>
                    resolve(data);
                });
                return cb();
            }, (err) => {
                this.logout();
                reject(err);
                return cb(err);
            });
        });
    }
    <%_ } _%>
    <%_ if (authenticationType === 'jwt') { _%>

    loginWithToken(jwt, rememberMe) {
        return this.authServerProvider.loginWithToken(jwt, rememberMe);
    }
    <%_ } _%>
    <%_ if (authenticationType === 'uaa') { _%>

    isAuthenticated() {
        return this.accountService.isAuthenticated();
    }

    logoutDirectly() {
        this.accountService.authenticate(null);
    }
    <%_ } _%>

    logout() {
        <%_ if (authenticationType === 'uaa') { _%>
        if (this.accountService.isAuthenticated()) {
            this.authServerProvider.logout().subscribe(() => this.accountService.authenticate(null));
        } else {
            this.accountService.authenticate(null);
        }
        <%_ } else if (authenticationType === 'oauth2') { _%>
        this.authServerProvider.logout().subscribe(response => {
            const data = response.body;
            let logoutUrl = data.logoutUrl;
            const redirectUri = `${location.origin}${this.location.prepareExternalUrl('/')}`;

            // if Keycloak, uri has protocol/openid-connect/token
            if (logoutUrl.indexOf('/protocol') > -1) {
                logoutUrl = logoutUrl + '?redirect_uri=' + redirectUri;
            } else {
                // Okta
                logoutUrl = logoutUrl + '?id_token_hint=' +
                    data.idToken + '&post_logout_redirect_uri=' + redirectUri;
            }
            window.location.href = logoutUrl;
        });
        <%_ } else { _%>
        this.authServerProvider.logout().subscribe(null, null, () => this.accountService.authenticate(null));
        <%_ } _%>
    }
}
